package cn.wolfcode.rbac.service.impl;

import cn.wolfcode.rbac.domain.Employee;
import cn.wolfcode.rbac.mapper.EmployeeMapper;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IEmployeeService;
import cn.wolfcode.rbac.service.IPermissionService;
import cn.wolfcode.rbac.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private IPermissionService permissionService;//登入时需要告知

    @Override
    @Transactional(readOnly = true)
    public void login(String username, String password) {
        Employee emp = this.employeeMapper.selectByInfo(username, password);
        if (emp == null) {
            throw new RuntimeException("账号和密码不匹配");
        }
        UserContext.setCurrentUser(emp);
        List<String> permission = this.permissionService.selectByEmpId(emp.getId());
        UserContext.setExpression(permission);
    }

    @Override
    @Transactional(readOnly = true)
    public PageInfo query(QueryObject paramQueryObject) {
        //分页总条数
        /*Integer rows = this.employeeMapper.selectForCount(paramQueryObject);
        if(rows.intValue()==0){
            return new PageResult(Integer.valueOf(paramQueryObject.getPageSize()));
        }
        List<Employee> list = this.employeeMapper.selectForList(paramQueryObject);
        return new PageResult(Integer.valueOf(paramQueryObject.getCurrentPage()),rows,list,Integer.valueOf(paramQueryObject.getPageSize())); */
        PageHelper.startPage(paramQueryObject.getCurrentPage(), paramQueryObject.getPageSize());
        List<Employee> list = this.employeeMapper.selectForList(paramQueryObject);
        return new PageInfo(list);
    }

    @Override
    //ids是对角色修改使用的。保存信息的
    public void saveOrUpdate(Employee entity, Long[] ids) {
        if (entity.getId() == null) {
            String password = entity.getPassword();
            Md5Hash md5Hash = new Md5Hash(password, entity.getName());
            //Md5Hash md5Hash = new Md5Hash(password);
            entity.setPassword(md5Hash.toString());
            this.employeeMapper.insert(entity);
        } else {
            this.employeeMapper.updateByPrimaryKey(entity);
            this.employeeMapper.deleteRelation(entity.getId());
            //对原有角色删除
        }
        //权限表需要插入
        if (ids != null && (ids.length > 0)) {
            for (Long roleId : ids) {
                this.employeeMapper.insertRelation(entity.getId(), roleId);
            }
        }
    }

    @Override
    public void delete(Long paramLong) {
        this.employeeMapper.deleteByPrimaryKey(paramLong);
        this.employeeMapper.deleteRelation(paramLong);
        //删除中间表的对应计入
    }

    @Override
    @Transactional(readOnly = true)
    public Employee get(Long id) {
        return this.employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Employee> list() {
        return this.employeeMapper.selectAll();
    }

    @Override
    public void abtchDelete(Long[] ids) {
        this.employeeMapper.abtchDelete(ids);
        for (Long id : ids) {
            this.employeeMapper.deleteRelation(id);
        }
    }

    @Override
    @Transactional(readOnly = true)
    public Long checkedName(String name) {
        return this.employeeMapper.checkedName(name);
    }

    @Override
    public Workbook exportXls() {
        //创建一个.xls文件
        Workbook workbook = new HSSFWorkbook();
        //创建SHEET，给SHEET起名和不起名的实现
        Sheet sheet = workbook.createSheet("员工名单");
        //创建行，从0开始
        Row row = sheet.createRow(0);
        //创建列，实际就是创建单元格
        Cell cell = row.createCell(0);
        //设置内容到单元格
        //cell.setCellValue("wolfcode");
        //对单元格的操作，写表头信息
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        //查询员工数据
        List<Employee> employees = employeeMapper.selectAll();
        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            //创建行
            row = sheet.createRow(i + 1);
            //设置单元格内容
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }
        return workbook;
    }

    //导入
    /*@Override
    public void importXls(MultipartFile file) throws IOException {
        //读取接收到的模板文件 XLS 并操作
        Workbook workbook = new HSSFWorkbook(file.getInputStream());
        //读取SHEET
        Sheet sheet = workbook.getSheetAt(0);
        //先获取总行数（下标索引号），索引从0开始
        int lastRowNum = sheet.getLastRowNum();
        //从索引为1的行数开始取数。循环要从1开始
        for (int i = 1 ; i <= lastRowNum ; i++){
            //在循环里，获取每行的内容
            Row row = sheet.getRow(i);
            //保存到数据库
            Employee employee = new Employee();
            employee.setName(row.getCell(0).getStringCellValue());
            employee.setEmail(row.getCell(1).getStringCellValue());
            employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
            //Md5Hash md5Hash = new Md5Hash(row.getCell(0).getStringCellValue()+1);
            employee.setPassword("1");
            this.saveOrUpdate(employee,null);
        }
    }*/
    @Override
    public void importXls(MultipartFile file) throws IOException {
        //读取接收到的模板文件XLS并操作
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读取Sheet
        Sheet sheet = wb.getSheetAt(0);
        //先获取总行数（行的下表索引号），索引从零开始
        int lastRowNum = sheet.getLastRowNum();
        System.out.println(lastRowNum);
        //从索引为一的行数开始取数。循环要从1开始
        for (int i = 1; i <= lastRowNum; i++) {
            //在循环里获取每行的内容。
            Row row = sheet.getRow(i);
            Employee employee = new Employee();
            //getxxxCellValue()要与XLS单元格的类型保持一致
            employee.setName(row.getCell(0).getStringCellValue());
            employee.setEmail(row.getCell(1).getStringCellValue());
            employee.setAge((int) row.getCell(2).getNumericCellValue());
            employee.setPassword("1");
            //保存到数据库
            this.saveOrUpdate(employee, null);
        }
    }
}
